<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24/024
 * Time: 22:38
 */

namespace app\admin\model;


use think\Model;

class Auth extends Model
{


    /**
     * 获取单条
     * @param $id
     * @return array|null|\PDOStatement|string|Model
     */
    public function _findOne($id){
        return $this->where(['id' => $id])->find();
    }


    /**
     * 详情
     * @param $id
     * @return array
     */
    public function _detail($id){
        $data = $this->where(['id' => $id])->find()->toArray();
        if($data['level'] == 1){
            $data['parent_auth_id'] = 0;
            $data['parent_auth_name'] = '无';
            $data['parent_auth_sort'] = '';
        }else{
            $parent_auth = $this->field('id,name,sort')->where(['id' => $data['pid']])->find()->toArray();
            $data['parent_auth_id'] = $parent_auth['id'];
            $data['parent_auth_name'] = $parent_auth['name'];
            $data['parent_auth_sort'] = $parent_auth['sort'];
        }
        return $data;
    }


    /**
     * 列表
     * @param array $condition
     * @param int $page_size
     * @param string $order_by
     * @return \think\Paginator
     */
    public function _list($condition = [], $page_size = PAGE_SIZE_ADMIN, $order_by = 'path, sort asc'){
        $obj = $this->order($order_by);
        $result = get_page($obj, $condition, $page_size);
        return $result;
    }


    /**
     * 获取父级权限--添加权限-搜索父级
     * @return array|string
     */
    public function _getParentAuth(){
        $condition = [
            ['level', 'in', [1,2]]
        ];
        $data = $this->field('id,auth_name,path,level')->where($condition)->order('path, sort asc')->select()->toArray();
        $add_data = [
            'id' => 0,
            'name' => '无',
            'path' => '',
            'level' => 0,
        ];
        array_unshift($data, $add_data);
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        return $data;
    }
    
    /**
    * 获取所有权限
    *
    */
    public function _getAuthAll($where = []){
        $data = $this->field('id, pid, auth_name,path,level')->where($where)->order('path, sort asc')->select()->toArray();
        return $data;
    }

    /**
     * 添加
     * @param $post
     * @return bool
     */
    public function _create($post){
        $level = 1;
        $path = '';
        if($post['pid']){
            $result = $this->find($post['pid']);
            if(!$result){
                $this->error = '父级权限不存在';
                return false;
            }
            $level = $result->level + 1;
            $path = $result->path;
        }
        
        if($level > 3){
            $this->error = '系统暂支持3级';
            return false;
        }
        
       if($level != 1){
            if(!$post['controller']){
                $this->error = '请填写控制器名称';
                return false;
            }
           if(!$post['action']){
               $this->error = '请填写方法名称';
               return false;
           }
       }
       
        // 启动事务
        $this->startTrans();
        $insert_data = [
            'level' => $level,
            'pid' => (int)$post['pid'],
            'auth_name' => trim($post['name']),
            'controller' => trim($post['controller']),
            'action' => trim($post['action']),
            'updated' => time(),
            'created' => time(),
        ];
        try {
            //写入数据
            
            $this->save($insert_data);
            
            $id = $this->id;
            
            $users = $this->where([['id', '=' ,$id]])->find();
            if(empty($path)){
                $path = $id;
            }else{
                //var_dump($id);
                $id = sprintf("%05d", $id);
                //var_dump($path);
                //var_dump(preg_match("/\./", $path));die;
                if(preg_match("/\./", $path)){
                    $path .= $id;
                }else{
                    $path = $path.'.'.$id;
                    //echo 2;
                }
            }
            //var_dump($id);
            //var_dump($path);die;
            $users->path = $path;
            $users->save();
            // 提交事务
            $this->commit();
            return true;
        } catch (\Exception $e) {
            //var_dump($e->getMessage());
            // 回滚事务
            $this->rollback();
            $this->error = '添加权限失败';
            return false;
        }
        
    }


    /**
     * 编辑
     * @param $post
     * @return bool
     */
    public function _modify($post){
        $id = (int)$post['id'];
        $users = $this->where([['id', '=' ,$id]])->find();
        if(empty($users)){
            $this->error = '没有此权限';
            return false;
        }
        
        if($id == $post['pid']){
            $this->error = '两级权限不能为同一个';
            return false;
        }
        
        $level = 1;
        $path = '';
        if($post['pid']){
            $result = $this->find($post['pid']);
            if(!$result){
                $this->error = '父级权限不存在';
                return false;
            }
            $level = $result->level + 1;
            $path = $result->path;
        }
        if($level > 3){
            $this->error = '系统暂支持3级';
            return false;
        }
        $ousers = $this->where([['auth_name', '=', trim($post['name'])]])->find();
        if(!empty($ousers) && ($ousers->id != $id)){
            $this->error = '该权限已存在';
            return false;
        }
        
        $users = $this->where([['id', '=' ,$id]])->find();
        if(empty($path)){
            $path = $id;
        }else{
            $id = sprintf("%05d", $id);
            if(preg_match("/\./", $path)){
                $path .= $id;
            }else{
                $path = $path.'.'.$id;
            }
        }
        
        $users->path = $path;
        $users->level = $level;
        $users->pid = (int)$post['pid'];
        $users->auth_name = trim($post['name']);
        $users->controller = trim($post['controller']);
        $users->action = trim($post['action']);
        $users->updated = time();
        
        $ret = $users->save();
        //var_dump($ret);
        if($ret === false){
            $this->error = '修改权限失败';
            return false;
        }
        return true;
    }


    /**
     * 删除
     * @param $id
     * @return bool
     */
    public function _remove($id){
        $this->startTrans();
        $auth = $this->where(['id' => $id])->find();
        if(empty($auth)){
            $this->error = '无此权限';
            return false;
        }
        if($auth->is_can_del == -1){
            $this->error = '该权限不能删除';
            return false;
        }
        $path = $auth->path;
        try {
            //校验是否为一级
            $ret = true;
            $ret1 = true;
            if(!preg_match('/\./', $path)){
                //一级分类
                $ret = $this->where([['id', '=', $id], ['is_can_del', '=', '1']])->delete();
                $where = [['path', 'REGEXP', "^{$path}\."], ['is_can_del', '=', '1']];
                $ret1 = $this->where($where)->delete();
                
            }else{
                //其他分类
                $path = str_replace('.','\\.', $path);
                $where = [['path', 'REGEXP', "^{$path}"], ['is_can_del', '=', '1']];
                $ret = $this->where($where)->delete();
            }
            if($ret && $ret1){
                // 提交事务
                $this->commit();
                return true;
            }else{
                $this->rollback();
                $this->error = '删除失败';
                return false;
            }
            
        } catch (\Exception $e) {
            //var_dump($e->getMessage());
            // 回滚事务
            $this->rollback();
            $this->error = '删除失败';
            return false;
        }

        
    }


    /**
     * 获取权限菜单
     * @param array $condition:
     * @param bool $is_all: 0两级，1三级
     * @param string $order
     * @return array
     */
    public function _getAuth($condition = [], $is_all = false, $order= 'sort asc'){
        $condition_1 = $condition_2 = $condition_3 = $condition;
        $condition_1[] = ['level', '=', 1];
        $condition_2[] = ['level', '=', 2];
        $condition_3[] = ['level', '=', 3];
        $level_1 = $this->where($condition_1)->order($order)->select()->toArray();
        $level_2 = $this->where([$condition_2])->order($order)->select()->toArray();
        $level_3 = [];
        if($is_all) $level_3 = $this->where($condition_3)->order($order)->select()->toArray();
        $data = [];
        if($level_3){
            foreach ($level_2 as $k => $v){
                foreach ($level_3 as $kk => $vv){
                    if($v['id'] == $vv['pid']){
                        $level_2[$k]['son'][] = $vv;
                    }
                }
            }
        }
        foreach ($level_1 as $k => $v){
            $data[] = $v;
            foreach ($level_2 as $kk => $vv){
                if($v['id'] == $vv['pid']){
                    $data[$k]['son'][] = $vv;
                }
            }
        }
        return $data;
    }
    
    /**
    * 获取条件
    */
    public function _where($request){
        $p = isset($request['page']) ? $request['page'] : 1;
        $start = isset($request['start']) ? $request['start'] : '';
        $end = isset($request['end']) ? $request['end'] : '';
        $role_id = isset($request['role_id']) ? $request['role_id'] : '';
        $title = isset($request['title']) ? $request['title'] : '';
        
        $request['page'] = $p;
        $request['start'] = $start;
        $request['end'] = $end;
        $request['title'] = $title;
        $request['role_id'] = $role_id;
        
        $search = $request;
        
        $title = htmlspecialchars(addslashes(str_replace(' ', '', $request['title'])));
        $request['title'] = str_replace('%', "\%", $title);
        
        $tmp = $request;
        foreach($tmp as $k=>$v){
            if(empty($v)){
                unset($tmp[$k]);
            }
        }
        
        $where = '';
        foreach($tmp as $k=>$v){
            if($k == 'start'){
                $start = strtotime($v);
                $where .= "created >= $start and ";
            }elseif($k == 'end'){
                $end = strtotime($v) + 24*3600;
                $where .= "created <= $end and ";
            }elseif($k == 'title'){
                $where .= "auth_name like '%$v%' and ";
            }
        }
        if(!empty($where)){
            $where = substr($where, 0, -4);
        }
        return array('search'=>$search,'where'=>$where);
    }
    
    /**
    * 数据总条数
    */
    public function _count($where = []){
        return $this->where($where)->count();
    }
    
    //校验权限名是否存在
    public function _checkName($value){
        $data = $this->where([['auth_name', '=', $value]])->find();
        if(!empty($data)){
            $this->error = '该权限已存在';
            return false;
        }
        return true;
    }

}